<template>
  <div
    style="
      width: 1000px;
      padding-bottom: 10px;
      margin: 20px auto;
      background-color: #fff;
      border-radius: 10px;
    "
  >
    <div
      style="
        height: 40px;
        margin-bottom: 10px;
        line-height: 40px;
        background-color: #eee;
        border-radius: 10px 10px 0 0;
      "
    >
      <span style="margin-left: 40px">基础信息</span>
    </div>
    <div style="margin-right: 40px">
      <el-form
        :model="formData"
        label-width="120px"
        :rules="formRules"
        label-position="right"
      >
        <!-- 基础信息部分 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品类型" required>
              <el-radio-group
                v-model="formData.productType"
                @change="handleProductTypeChange"
              >
                <el-radio value="10">电脑</el-radio>
                <el-radio value="11">手机</el-radio>
                <el-radio value="12">耳机</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品单位" prop="productUnit">
              <el-input v-model="formData.productUnit" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productId">
              <el-input
                v-model="formData.productId"
                placeholder="根据分类自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName" required>
              <el-input v-model="formData.productName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12"
            ><el-form-item label="封面图:" prop="coverImage">
              <el-upload
                class="avatar-uploader"
                :action="host + '/upload'"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="轮播图:" prop="carouselImage">
              <el-upload
                class="avatar-uploader"
                :action="host + '/upload'"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload1"
                :on-success="handleAvatarSuccess1"
              >
                <img v-if="imageUrl1" :src="imageUrl1" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品分类" required>
              <el-select
                v-model="formData.productCategory"
                :disabled="!formData.productType"
                placeholder="下拉选择二级分类"
                clearable
              >
                <el-option
                  v-for="productCategory in filteredproductCategorys"
                  :key="productCategory.value"
                  :label="productCategory.label"
                  :value="productCategory.value"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="型号" required>
              <el-select
                v-model="formData.model"
                placeholder="下拉选择已创建型号"
                clearable
              >
                <el-option label="安卓" value="10" />
                <el-option label="苹果" value="20" />
                <el-option label="鸿蒙" value="30" />
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格条码" prop="specificationBarcode">
              <el-input
                v-model="formData.specificationBarcode"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="规格编码" prop="specificationCode">
              <el-input
                v-model="formData.specificationCode"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select
                v-model="formData.brand"
                placeholder="下拉选择"
                clearable
              >
                <el-option label="java" value="java" />
                <el-option label="mysql" value="mysql" />
                <el-option label="vue" value="vue" />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="材质">
              <el-select
                v-model="formData.material"
                placeholder="下拉选择二级分类"
                clearable
              >
                <el-option label="铝合金" value="铝合金" />
                <el-option label="钛合金" value="铝合金" />
                <el-option label="锡合金" value="铝合金" />
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单重" prop="quantity">
              <el-input
                v-model="formData.quantity"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="外形尺寸" prop="dimensions">
              <el-input
                v-model="formData.dimensions"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品图号" prop="productModel">
              <el-input
                v-model="formData.productModel"
                placeholder="请输入 小米产品为非必填，其他为必填"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="工厂图号" prop="factoryNumber">
              <el-input
                v-model="formData.factoryNumber"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原装图号" prop="originalNumber">
              <el-input
                v-model="formData.originalNumber"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="inventory">
              <el-input
                v-model="formData.inventory"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price" required>
              <el-input
                v-model="formData.price"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="排序" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="低库存预警值" prop="lowStockAlert">
              <el-input
                v-model="formData.lowStockAlert"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="高库存预警值" prop="highStockAlert">
              <el-input
                v-model="formData.highStockAlert"
                placeholder="请输入"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="品牌资料" prop="brandDetail">
          <el-input
            v-model="formData.brandDetail"
            style="width: 100%"
            :rows="5"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="产品详情" prop="productDetail">
          <el-input
            v-model="formData.productDetail"
            style="width: 100%"
            :rows="5"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import router from "@/router";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import host from "@/utils/env.js";
import { saveProduct } from "@/api/product/product.js";
import { computed } from "vue";
//产品分类
const productCategorys = {
  10: [
    { value: 1, label: "dell电脑" },
    { value: 2, label: "天选电脑" }
  ],
  11: [
    { value: 1, label: "vivo手机" },
    { value: 2, label: "小米手机" }
  ],
  12: [
    { value: 1, label: "漫步者耳机" },
    { value: 2, label: "水月雨耳机" }
  ]
};
// 计算属性动态过滤选项
const filteredproductCategorys = computed(() => {
  return productCategorys[formData.value.productType] || [];
});

// 处理产品类型变化
const handleProductTypeChange = () => {
  formData.value.productCategory = ""; // 清空已选
  filteredproductCategorys.value = [...filteredproductCategorys.value];
};

//-----------------图片上传
const imageUrl = ref("");
//上传前
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("请选择jpg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("图片不能超过10M!");
    return false;
  }
  return true;
};

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    //显示图片
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    ElMessage.success("上传成功");
    //更改图片地址
    formData.value.coverImage = response.data;
  }
};
//-----------------------图片上传
const imageUrl1 = ref("");
//上传前
const beforeAvatarUpload1 = rawFile => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("请选择jpg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("图片不能超过10M!");
    return false;
  }
  return true;
};

//上传成功
const handleAvatarSuccess1 = (response, uploadFile) => {
  if (response.code == 200) {
    //显示图片
    imageUrl1.value = URL.createObjectURL(uploadFile.raw);
    ElMessage.success("上传成功");
    //更改图片地址
    formData.value.coverImage = response.data;
  }
};
//-----------------------图片上传

const formData = ref({
  productType: "",
  productUnit: "",
  productId: "",
  productName: "",
  coverImage: "",
  carouselImage: "",
  productCategory: "",
  model: "",
  specificationBarcode: "",
  specificationCode: "",
  brand: "",
  material: "",
  quantity: "",
  dimensions: "",
  productModel: "",
  factoryNumber: "",
  originalNumber: "",
  inventory: "",
  price: "",
  sort: "",
  lowStockAlert: "",
  highStockAlert: "",
  brandDetail: "",
  productDetail: ""
});

//表单验证
const formRules = ref({
  productType: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  productName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  productCategory: [
    { required: true, message: "二级分类不能为空", trigger: "blur" }
  ],
  model: [{ required: true, message: "型号不能为空", trigger: "blur" }],
  price: [{ required: true, message: "价格不能为空", trigger: "blur" }]
});

async function save() {
  let res = await saveProduct(formData.value);
  if (res.code == 200) {
    router.push("/product/list");
    ElMessage({
      message: "添加成功",
      type: "success"
    });
  }
}

const handleSubmit = () => {
  // 表单提交逻辑
  console.log("提交数据：", formData);
  // 提交成功后跳转到列表页面
  save();
};

const handleCancel = () => {
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = "";
  });
  // 取消后跳转到列表页面
  router.push("/product/list");
};
</script>
<style scoped>
:deep(.avatar-uploader .avatar) {
  display: block;
  width: 108px;
  height: 108px;
}

:deep(.avatar-uploader .el-upload) {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  width: 108px;
  height: 108px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
